import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Table, TableProps} from 'antd';
import type {Employee} from "@/types/resp/employee";
import employeeApi from '@/api/employeeApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import DepartmentSelector from "@/pages/department/DepartmentSelector.tsx";
import PositionSelector from "@/pages/position/PositionSelector.tsx";


interface EmployeeSelectorProps {
  visible: boolean;
  onEmployeeSelected: (selectedEmployee: { employeeId?: number; employeeName?: string; }) => void;
  onCloseEmployeeSelector: () => void;
}

const EmployeeSelector: React.FC<EmployeeSelectorProps> = ({visible, onEmployeeSelected, onCloseEmployeeSelector}) => {

  const [employeeSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    employeeSelectorForm.resetFields();
  };

  const [data, setData] = useState<Employee[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Employee>> = await employeeApi.find(employeeSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Employee> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Employee>['columns'] = [
    {title: '企业名称', dataIndex: 'enterpriseName', key: 'enterpriseName'},
    {title: '工号', dataIndex: 'employeeNumber', key: 'employeeNumber'},
    {title: '姓名', dataIndex: 'name', key: 'name'},
    {title: '密码', dataIndex: 'password', key: 'password'},
    {title: '性别', key: 'gender', render: (_, record) => (
        <span>
        {(function () {
          if (record.gender === 1) return '男';
          else if (record.gender === 2) return '女';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '出生日期', key: 'birthDate', render: (_, record) => (
      <div>{record.birthDate.format('YYYY-MM-DD')}</div>
    )},
    {title: '联系电话', dataIndex: 'contactPhone', key: 'contactPhone'},
    {title: '邮箱', dataIndex: 'email', key: 'email'},
    {title: '省', dataIndex: 'provinceName', key: 'province'},
    {title: '市', dataIndex: 'cityName', key: 'city'},
    {title: '区', dataIndex: 'areaName', key: 'area'},
    {title: '家庭地址', dataIndex: 'address', key: 'address'},
    {title: '聘用日期', key: 'hireDate', render: (_, record) => (
      <div>{record.hireDate.format('YYYY-MM-DD')}</div>
    )},
    {title: '部门名称', dataIndex: 'departmentName', key: 'departmentName'},
    {title: '岗位名称', dataIndex: 'positionName', key: 'positionName'},
  ];

  const handleRowDoubleClick = (row: Employee) => {
    onEmployeeSelected({
      employeeId: row.id,
      employeeName: row.name,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseEmployeeSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);

  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      employeeSelectorForm.setFieldsValue(Object.assign(employeeSelectorForm.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [departmentSelectorVisible, setDepartmentSelectorVisible] = useState(false);
  const findDepartment = () => {
    setDepartmentSelectorVisible(true);
  }
  const handleDepartmentSelected = (selectedDepartment: { departmentId?: number; departmentName?: string; }) => {
    setDepartmentSelectorVisible(false)
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      employeeSelectorForm.setFieldsValue(Object.assign(employeeSelectorForm.getFieldsValue(), {
      departmentId: selectedDepartment['departmentId'],
      departmentName: selectedDepartment['departmentName'],
      }));
    }
  };
  const handleCloseDepartmentSelector = () => {
    setDepartmentSelectorVisible(false)
  };
  const [positionSelectorVisible, setPositionSelectorVisible] = useState(false);
  const findPosition = () => {
    setPositionSelectorVisible(true);
  }
  const handlePositionSelected = (selectedPosition: { positionId?: number; positionName?: string; }) => {
    setPositionSelectorVisible(false)
    if (selectedPosition && 'positionId' in selectedPosition) {
      employeeSelectorForm.setFieldsValue(Object.assign(employeeSelectorForm.getFieldsValue(), {
      positionId: selectedPosition['positionId'],
      positionName: selectedPosition['positionName'],
      }));
    }
  };
  const handleClosePositionSelector = () => {
    setPositionSelectorVisible(false)
  };

  return (
    <Modal title={"员工基本信息选择器(双击行选中)"} open={visible} onCancel={onCloseEmployeeSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={employeeSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="enterpriseName" label="企业名称">
          <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
        </Form.Item>
        <Form.Item name="employeeNumber" label="工号">
          <Input maxLength={32} placeholder="请输入工号"/>
        </Form.Item>
        <Form.Item name="name" label="姓名">
          <Input maxLength={64} placeholder="请输入姓名"/>
        </Form.Item>
        <Form.Item name="departmentName" label="部门名称">
          <Input.Search placeholder="请选择部门名称" onSearch={findDepartment} readOnly={true} />
        </Form.Item>
        <Form.Item name="positionName" label="岗位名称">
          <Input.Search placeholder="请选择岗位名称" onSearch={findPosition} readOnly={true} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<Employee> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         scroll={{ x: 'max-content' }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <DepartmentSelector visible={departmentSelectorVisible} onDepartmentSelected={handleDepartmentSelected} onCloseDepartmentSelector={handleCloseDepartmentSelector} />
      <PositionSelector visible={positionSelectorVisible} onPositionSelected={handlePositionSelected} onClosePositionSelector={handleClosePositionSelector} />
    </Modal>
  );
};

export default EmployeeSelector;
